<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>列表</title>
</head>
<body>
    <select id="city">
        <option value="cd">成都</option>
        <option value="my">绵阳</option>
        <option value="dy">德阳</option>
        <option value="nc">南充</option>
    </select>
    <select id="province" multiple>
        <option value="sc">四川</option>
        <option value="yn">云南</option>
        <option value="cq">重庆</option>
        <option value="sh">上海</option>
    </select>
    <input type="button" value="增加" id="addBtn">
    <input type="button" value="删除" id="removeBtn">
    <input type="button" value="获取选中" id="getBtn">
    <script>   
        let city = document.getElementById("city");
        document.getElementById("addBtn").onclick = function(){
            // console.log('add');
            // let opt = document.createElement("option");
            // let text = document.createTextNode("内江");
            // opt.appendChild(text);
            // opt.value = "nj";
            // city.appendChild(opt);

            // city.innerHTML += '<option value="jy">简阳</option>'
            let opt = new Option("内江","nj");
            city.add(opt);
        }
        document.getElementById("removeBtn").onclick = function(){
            // city.remove(0);
            // 快速删除所有option节点的方法
            city.options.length = 0;
        }
        document.getElementById("getBtn").onclick = function(){
            // 获取下拉列表选中元素的value值
            console.log(city.value);
            // 获取下拉列表选中元素的文本内容
            // selectedIndex获取选中元素的下标值
            console.log(city.options[city.selectedIndex].text);
            // 如果是多选列表，value和selectedIndex只能获取第一个元素
            console.log(province.value);
            console.log(province.options[province.selectedIndex].text);
            // 循环列表，判断元素是否被选中
            for(let i = 0;i < province.options.length;i++){
                if(province.options[i].selected){
                    console.log(province.options[i].value,province.options[i].text);
                }
            }
        }
    </script>
</body>
</html>